package com.gxuwz.medical.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.gxuwz.medical.config.Constant;
import com.gxuwz.medical.domain.menu.Menu;
import com.gxuwz.medical.domain.role.Role;
import com.gxuwz.medical.domain.user.User;
import com.gxuwz.medical.exception.UserNotFoundException;

/**
 * 登录验证控制模块
 * 
 * @author 演示
 * 
 */

public class LoginServlet extends BaseServlet {

	private static final long serialVersionUID = 7279138098299110478L;
	private static final Logger LOG = LogManager.getLogger(LoginServlet.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		login(request, response);

	}

	private void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String path = "login.jsp";
		// LOG.info("用户登录");
		try {
			String userid = request.getParameter("userid");
			String pwd = request.getParameter("pwd");
			User user = new User(userid, pwd);
			for (Role role : user.getRoles()) {
				for (Menu menu : role.getMenus()) {
					String name = menu.getMenuid();
					String value = menu.getMenuid();
					request.getSession().setAttribute(name, value);
				}
			}
			// 绑定会话编号
			request.getSession().setAttribute("agencode", user.getAgencode());
			request.getSession().setAttribute("userName", user.getFullname());
			request.getSession().setAttribute(Constant.IDENTIFIER,
					Constant.IDENTIFIER);
			path = "index.jsp";
		} catch (UserNotFoundException e) {

			path = "login.jsp";
		}
		// 跳转页面
		process(request, response, path);

	}

}
